import time
import requests
from config import CITY_ID_MAP

SESSION = requests.Session()
SESSION.headers.update({
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Damai/7.2.0",
    "Referer": "https://m.damai.cn/",
    "Origin": "https://m.damai.cn",
    "Accept": "application/json, text/plain, */*",
})

def city_to_id(city: str) -> str:
    return CITY_ID_MAP.get(city.strip(), CITY_ID_MAP.get("北京"))

def search(city_name: str, keyword: str = "", category: int = 0, page: int = 1) -> dict:
    url = "https://search.damai.cn/searchajax.html"
    params = {
        "city": city_to_id(city_name),
        "keyword": keyword,
        "ctl": category,
        "page": page,
        "ts": int(time.time() * 1000),
        "stype": 0,
        "order": 1,
    }
    resp = SESSION.get(url, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

def list_cities() -> dict:
    return CITY_ID_MAP
